/**
 * 
 */
package com.agilegroup.crm.ui.fragments;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockDialogFragment;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.agilegroup.crm.AgileApplication;
import com.agilegroup.crm.R;
import com.agilegroup.crm.adapters.ContactAdapter;
import com.agilegroup.crm.model.ContactData;
import com.agilegroup.crm.model.ContactList;
import com.agilegroup.crm.requests.ContactsJsonRequest;
import com.agilegroup.crm.ui.ListDialogActivity;
import com.agilegroup.crm.ui.NewContactActivity;
import com.agilegroup.crm.ui.ViewContactActivity;
import com.agilegroup.crm.utils.ContactsSync;
import com.agilegroup.crm.utils.OnlineChecker;
import com.agilegroup.crm.utils.SessionManager;
import com.octo.android.robospice.persistence.DurationInMillis;
import com.octo.android.robospice.persistence.exception.CacheLoadingException;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;

/**
 * @author Hisham
 *
 */
public class ContactFragment extends SherlockListFragment{
	 
		private SessionManager sessionManager;
		private static final String JSON_CACHE_KEY = "contacts_json";
		private OnlineChecker checker;
		
	    @Override
	    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	            Bundle savedInstanceState) {
	        
	        
	        return super.onCreateView(inflater, container, savedInstanceState);
	    }
	    @SuppressWarnings("static-access")
		@Override
	    public void onCreate(Bundle savedInstanceState) {
	    	super.onCreate(savedInstanceState);
	    	setRetainInstance(true);
	    	setHasOptionsMenu(true);
	    	checker = new OnlineChecker(getActivity());
	    	sessionManager = new SessionManager(getSherlockActivity());    
	     	HashMap<String, String> user = sessionManager.getUserDetails();
	     	String empId = user.get(sessionManager.KEY_ID);
	     	AgileApplication.getInstance().spiceManager.execute(new ContactsJsonRequest(empId),JSON_CACHE_KEY,DurationInMillis.ALWAYS_EXPIRED,new ContactListJsonRequestListener());
	    }
	    public class ContactListJsonRequestListener implements RequestListener<ContactList>{

			public void onRequestFailure(SpiceException spiceException) {
				Toast.makeText(getSherlockActivity(), "Failure", Toast.LENGTH_SHORT).show();
				getListView().clearAnimation();
			}

			public void onRequestSuccess(ContactList result) {
				List<ContactData>contactData = result.getContactData();
				if (contactData.size()==0) {
					setEmptyText(getResources().getString(R.string.no_data));
				}
				ContactAdapter adapter = new ContactAdapter(getSherlockActivity(), contactData);
				setListAdapter(adapter);
			}

		 }
	    @Override
	    public void onListItemClick(ListView l, View v, int position, long id) {
	    	TextView contactId = (TextView)v.findViewById(R.id.txtid);
	    	if(checker.isOnline()==true){
	    		Intent view = new Intent(this.getSherlockActivity(),ViewContactActivity.class);
	    		view.putExtra("contactId", contactId.getText().toString());
	    		getSherlockActivity().startActivity(view);
	    	}
	    	else{
	    		SherlockDialogFragment dialogFragment = new ConnectionDialogFragment();
    			dialogFragment.show(getSherlockActivity().getSupportFragmentManager(), "connectionDialog");
	    	}
	    }

	    @Override
	    public void onActivityCreated(Bundle savedInstanceState) {
	    	super.onActivityCreated(savedInstanceState);
	    	
	    	OnItemLongClickListener longClickListener = new OnItemLongClickListener() {
				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					Intent listDialog = new Intent(ContactFragment.this.getSherlockActivity(),ListDialogActivity.class);
					TextView leadId = (TextView)arg1.findViewById(R.id.txtid);
					TextView email = (TextView)arg1.findViewById(R.id.txtEmail);
					TextView mobile = (TextView)arg1.findViewById(R.id.txtMobile);
					
					listDialog.putExtra("listDialog", "3");
					listDialog.putExtra("leadId", leadId.getText().toString());
					listDialog.putExtra("email", email.getText().toString());
					listDialog.putExtra("mobile", mobile.getText().toString());
					ContactFragment.this.getSherlockActivity().startActivity(listDialog);
					return false;
				}
			};
			getListView().setOnItemLongClickListener(longClickListener);
	    }
	    
	    @Override
		public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
			inflater.inflate(R.menu.contacts_menu, menu);
			super.onCreateOptionsMenu(menu, inflater);
		}
		@SuppressWarnings("static-access")
		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			switch (item.getItemId()) {
			case R.id.action_refresh_contacts:
					HashMap<String, String> user = sessionManager.getUserDetails();
					String empId = user.get(sessionManager.KEY_ID);
					AgileApplication.getInstance().spiceManager.execute(new ContactsJsonRequest(empId),JSON_CACHE_KEY,DurationInMillis.ALWAYS_EXPIRED,new ContactListJsonRequestListener());
				break;
			case android.R.id.home:
				getActivity().finish();
			break;
			case R.id.action_sync_contacts:
				try {
					Future<ContactList> contactList = AgileApplication.getInstance().spiceManager.getDataFromCache(ContactList.class, JSON_CACHE_KEY);
					Log.d("contact data size", String.valueOf(contactList.get().getContactData().size()));
					//Toast.makeText(getSherlockActivity(), contactList.get().getContactData().toString(), Toast.LENGTH_SHORT).show();
					if(contactList.get().getContactData().size()==0){
						Toast.makeText(getSherlockActivity(), "There's no contact to sync", Toast.LENGTH_SHORT).show();
					}
					else{
						ContactsSync contactsSync = new ContactsSync(contactList.get().getContactData());
						contactsSync.createContacts(getSherlockActivity());
					}
				} catch (CacheLoadingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ExecutionException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			case R.id.action_new_contact:
					Intent newContact = new Intent(getSherlockActivity(),NewContactActivity.class);
					getSherlockActivity().startActivity(newContact);
				break;
			default:
				break;
			}
			return super.onOptionsItemSelected(item);
		}
	}